import react_native_blob_util from 'react-native-blob-util';

import { post, put } from '../utils/http';
import { DEVICE_ID } from '@/constants';
import { getStorageItem } from '@/utils/storage';

export const uploadAPI = {
  queryFileUrl: async (filename: string, signal?: AbortSignal) => {
    try {
      const data = {
        filename,
      };
      const { data: res } = await put<{
        code: number;
        msg: string;
        data: {
          uploadUrl: string;
          downloadUrl: string;
        };
      }>('/turning-oss/files/upload', data, { signal });
      return res.data;
    } catch (error) {
      console.log('queryFileUrl error', error);
      throw new Error('query file url failed');
    }
  },

  uploadFile: async (filePath: string, signal?: AbortSignal) => {
    try {
      const match = filePath.match(/\/([^/]+)$/);
      let fileName = '';
      if (match) {
        fileName = match[1];
      } else {
        throw new Error('Obtain file name failed');
      }
      const res = await uploadAPI.queryFileUrl(fileName, signal);
      await react_native_blob_util
        .fetch('PUT', res.uploadUrl, {}, react_native_blob_util.wrap(filePath))
        .uploadProgress((sent, total) => {
          console.log('uploadFile uploadProgress', sent, total);
        })
        .then((res2) => {
          console.log('uploadFile res', res2.respInfo.status);
        });
      // 上传成功后，返回下载地址
      return res.downloadUrl;
    } catch (error) {
      console.log('uploadFile error', error);
      throw new Error('upload file failed or canceled');
    }
  },
  async getGenerateHistory(params?: { nextId?: string; pageSize?: number; showAll?: boolean }) {
    try {
      const { data } = await post<{
        code: number;
        msg: string;
        data: { originalUrlList: { id: string; originalUrl: string }[] };
      }>('/rework-api/generate/history/photo/list', params);
      return data;
    } catch (error) {
      console.error(error);
      throw new Error('获取上传历史记录失败');
    }
  },
  async getUploadHistory(params?: { nextId?: string; pageSize?: number; showAll?: boolean }) {
    try {
      const { data } = await post<{
        code: number;
        msg: string;
        data: { originalUrlList: { id: string; originalUrl: string }[] };
      }>('/rework-api/upload/history/photo/list', params);
      return data;
    } catch (error) {
      console.error(error);
      throw new Error('获取上传历史记录失败');
    }
  },
  async saveUploadHistory(params?: { photoUrl: string }) {
    try {
      const { data } = await post<{
        code: number;
        msg: string;
        data: string;
      }>('/rework-api/upload/history/photo/save', params, {
        headers: {
          'ts-user-id': getStorageItem(DEVICE_ID),
        },
      });
      return data;
    } catch (error) {
      console.error(error);
      throw new Error('获取保存历史记录失败');
    }
  },
  async removeUploadHistory(params?: { id: string }) {
    try {
      const { data } = await post<{
        code: number;
        msg: string;
        data: boolean;
      }>('/rework-api/upload/history/photo/delete', params, {
        headers: {
          'ts-user-id': getStorageItem(DEVICE_ID),
        },
      });
      return data;
    } catch (error) {
      console.error(error);
      throw new Error('获取上传历史记录失败');
    }
  },
};
